package org.idea.qiyu.threadpool.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @Author linhao
 * @Date created in 11:31 上午 2021/10/16
 */
@Configuration
public class ThreadPoolConfig {


    @Bean
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(16);
        taskExecutor.setKeepAliveSeconds(30000);
        taskExecutor.setMaxPoolSize(64);
        taskExecutor.setQueueCapacity(512);
        return taskExecutor;
    }

    @Bean
    public ExecutorService emailTaskPool() {
        return new ThreadPoolExecutor(2, 4,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), new SysThreadFactory("email-task"));
    }

    @Bean
    public ExecutorService asyncTaskConsumerPool() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10,
                20L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50), new SysThreadFactory("email-task"));
        threadPoolExecutor.prestartAllCoreThreads();
        return threadPoolExecutor;
    }

    @Bean
    public ScheduledThreadPoolExecutor  scheduledThreadPoolExecutor(){
        return new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                thread.setName("org.idea.threadpool.beat.sender");
                return thread;
            }
        });
    }
}
